<template>
    <div class="box" v-if="!isError">
        <div class="min-h-screen bg-gray-50" v-if="!isLoading">
            <!-- 顶部导航 -->
            <header class="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm z-50">
                <div class="max-w-7xl mx-auto px-4 h-full flex items-center justify-between">
                    <div class="flex items-center">
                        <el-button class="!rounded-button" @click="retuenAssessment()">
                            <el-icon>
                                <ArrowLeft />
                            </el-icon>
                            返回
                        </el-button>
                    </div>
                    <h1 class="text-xl font-medium">题目测试</h1>
                    <div class="flex items-center space-x-4">
                        <div class="text-lg font-mono">{{ formatTime }}</div>
                    </div>
                </div>
            </header>

            <!-- 主体内容 -->
            <main class="pt-24 pb-32 max-w-4xl mx-auto px-4">
                <!-- 进度条 -->
                <div class="mb-8">
                    <el-progress :percentage="progress" :format="progressFormat" />
                </div>

                <!-- 题目信息 -->
                <div class="mb-6 flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                        <span class="text-lg font-medium">第 {{ currentIndex + 1 }} 题</span>
                        <el-tag :type="questions[currentIndex].type === '单选' ? 'primary' : 'success'">
                            {{ questions[currentIndex].type }}
                        </el-tag>
                        <div class="flex items-center space-x-1">
                            <span class="text-sm font-medium">难度：</span>
                            <div v-for="(_, index) in Array(questions[currentIndex].difficultyLevel).fill(0)" :key="index">
                                <el-icon>
                                    <Star />
                                </el-icon>
                            </div>
                        </div>
                    </div>
                    <el-button class="!rounded-button" @click="showQuestionList = true">
                        题目列表
                    </el-button>
                </div>

              
<!-- 题目内容 -->
<div class="bg-white rounded-lg p-6 shadow-sm mb-6">
    <div class="text-lg mb-6">{{ questions[currentIndex].questionContent }}</div>
    <div class="space-y-4">
        <div v-for="(option, index) in questions[currentIndex].options" :key="index" :class="[
            'p-4 rounded-lg border cursor-pointer transition-colors',
            {
                'border-primary-500 bg-primary-50': isSelected(index),
                'border-gray-200 hover:border-primary-500': !isSelected(index)
            }
        ]" @click="handleSelect(index)">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <!-- 添加ABCD选项 -->
                    <div :class="[
                        'w-6 h-6 rounded-full border-2 flex items-center justify-center',
                        {
                            'border-primary-500 text-primary-500': isSelected(index),
                            'border-gray-300 text-gray-500': !isSelected(index)
                        }
                    ]">
                        {{ String.fromCharCode(65 + index) }}
                    </div>
                    <span :class="{
                        'text-primary-500': isSelected(index)
                    }">{{ option }}</span>
                </div>
                <!-- 将勾选标记移到右边 -->
                <div v-if="isSelected(index)" class="text-primary-500">
                    <el-icon>
                        <Check />
                    </el-icon>
                </div>
            </div>
        </div>
    </div>
</div>
            </main>

            <!-- 底部操作栏 -->
            <footer class="fixed bottom-0 left-0 right-0 h-20 bg-white border-t">
                <div class="max-w-4xl mx-auto px-4 h-full flex items-center justify-between">
                    <el-button class="!rounded-button" :disabled="currentIndex === 0" @click="handlePrev">
                        上一题
                    </el-button>
                    <el-button class="!rounded-button" type="primary" @click="handleNext">
                        {{ isLastQuestion ? '提交' : '下一题' }}
                    </el-button>
                </div>
            </footer>

            <!-- 题目列表弹窗 -->
            <el-dialog v-model="showQuestionList" title="题目列表" width="500px">
                <div class="grid grid-cols-5 gap-4">
                    <div v-for="(_, index) in questions" :key="index" :class="[
                        'h-12 rounded-lg flex items-center justify-center cursor-pointer border',
                        {
                            'border-primary-500 bg-primary-50': index === currentIndex,
                            'border-gray-200': index !== currentIndex
                        }
                    ]" @click="jumpToQuestion(index)">
                        {{ index + 1 }}
                    </div>
                </div>
            </el-dialog>
        </div>
        <div v-else class="flex items-center justify-center h-screen">
            <div class="text-2xl">加载中...</div>
        </div>
    </div>
    <div v-else class="flex items-center justify-center h-screen">
        <div class="text-2xl text-red-500">加载题目失败</div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft, Star, Check } from '@element-plus/icons-vue';
import { getQuestionList, addScore } from '../../api/student/assessementCenter/stuAssessement';

const router = useRouter();
const route = useRoute();
const questionBankId = route.query.questionBankId;

console.log("Question Bank ID:", questionBankId);

// 题目数据
const questions = ref([]);
const currentIndex = ref(0);
const showQuestionList = ref(false);
const timer = ref(0);
let answers = ref([]);
const isLoading = ref(true);
const isError = ref(false);

// 进度条
const progress = computed(() => {
    return Math.round(((currentIndex.value + 1) / questions.value.length) * 100);
});

// 时间格式化
const formatTime = computed(() => {
    const minutes = Math.floor(timer.value / 60);
    const seconds = timer.value % 60;
    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
});

// 选项操作
const isSelected = (optionIndex) => {
    return answers.value[currentIndex.value].includes(optionIndex);
};

const handleSelect = (optionIndex) => {
    const currentAnswers = answers.value[currentIndex.value];
    const currentQuestion = questions.value[currentIndex.value];

    if (currentQuestion.type === '单选') {
        answers.value[currentIndex.value] = [optionIndex];
    } else {
        const index = currentAnswers.indexOf(optionIndex);
        if (index === -1) {
            answers.value[currentIndex.value] = [...currentAnswers, optionIndex];
        } else {
            answers.value[currentIndex.value] = currentAnswers.filter(i => i !== optionIndex);
        }
    }
};

// 导航操作
const isLastQuestion = computed(() => {
    return currentIndex.value === questions.value.length - 1;
});

const handlePrev = () => {
    if (currentIndex.value > 0) {
        currentIndex.value--;
    }
};

const handleNext = () => {
    if (isLastQuestion.value) {
        handleSubmit();
    } else {
        currentIndex.value++;
    }
};

const jumpToQuestion = (index) => {
    currentIndex.value = index;
    showQuestionList.value = false;
};

// 提交答案
const handleSubmit = async () => {
    ElMessageBox.confirm('确定要提交答案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            // 构造符合后端接口要求的参数
            const assessmentCenterDtos = questions.value.map((question, index) => {
                return {
                    id: question.id, // 题目id
                    assessmentId: questionBankId, // 假设评估的id是从其他地方获取的，例如从路由参数或接口中获取
                    answers: answers.value[index] // 用户的答案
                };
            });

            // 调用 addScore 方法，将 answers 传递到后端
            const response = await addScore(assessmentCenterDtos);

            // 处理提交成功逻辑
            ElMessage.success('提交成功！');
            console.log('提交结果：', response);

            // 跳转回测评中心
            retuenAssessment();

            // 重置状态
            resetState();
        } catch (error) {
            console.error('提交失败：', error);
            ElMessage.error('提交失败，请稍后再试');
        }
    });
};

// 重置状态（可选）
const resetState = () => {
    currentIndex.value = 0;
    answers.value = Array(questions.value.length).fill([]);
    timer.value = 0;
};

// 返回
const retuenAssessment = () => {
    router.push({ path: '/assessment' });
};

// 初始化加载题目
const fetchQuestions = async () => {
    try {
        const response = await getQuestionList(questionBankId);
        questions.value = response; // 假设返回的数据结构为 { data: { questions: [...] } }
        answers.value = Array(questions.value.length).fill([]);
        isLoading.value = false;
        startTimer();
    } catch (error) {
        console.error('加载题目失败:', error);
        isError.value = true;
    }
};

// 计时器
const startTimer = () => {
    setInterval(() => {
        timer.value++;
    }, 1000);
};

// 页面加载时执行
onMounted(() => {
    fetchQuestions();
});
</script>

<style scoped>
:deep(.el-progress-bar__inner) {
    transition: width 0.3s ease;
}

.border-primary-500 {
    border-color: #409EFF;
}

.bg-primary-50 {
    background-color: #ecf5ff;
}

.text-primary-500 {
    color: #409EFF;
}
</style>